# apps/monitoring/signals.py
from django.db.models.signals import post_migrate
from django.dispatch import receiver
from django.utils import timezone
from apps.rooms.models import Room
from .models import SensorReading, ActionLog
from .utils import log_action

@receiver(post_migrate)
def create_initial_messages(sender, **kwargs):
    """
    任何 app 完成 migrate 后都会触发一次；只要监控表还是空，就写基线。
    """
    # ---- A. 基线温湿度 --------------------------------------------------
    if not SensorReading.objects.exists():          # ★关键判断
        for room in Room.objects.all():
            SensorReading.objects.create(
                room=room, temperature=24.0, humidity=50.0,
                recorded_at=timezone.now()
            )
            print(f"[monitoring] 已写基线读数 -> {room.name}")

    # ---- B. 系统初始化日志 ----------------------------------------------
    if not ActionLog.objects.filter(action_type='系统初始化').exists():
        log_action(action_type='系统初始化',
                   old_value=None,
                   new_value='写入各房间 24℃/50% 基线')
        print("[monitoring] 已写初始化日志")